﻿Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.String
Imports IDServer
Imports System.Text
Imports System.Collections
Imports CrystalDecisions.CrystalReports.Engine


Public Class Frm_PURPOCount

    Implements IDServer.IDServer.IDServer
    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private mDataset As DataSet
    Private MasterDS As DataSet
    Private SelectNode As TreeNode
    Private Img As ImageList
    Public bFind As Boolean

    Private WithEvents MainForm As Frm_MainForm
    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

#Region "interface"
    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd

    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Try
            If App.ExportEnable = False Then
                MessageBox.Show(My.Resources.NotAllowExport, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            SaveXls(MasterDS.Tables(0))
        Catch ex As Exception
            MessageBox.Show(ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint
        Dim Frm As New Frm_Wating
        Try

            If MasterDS.Tables(0).Rows.Count <= 0 Then
                MsgBox(My.Resources.NoDatatoPrint, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Function
            End If
            If Me.DataGridView1.Rows.Count <= 0 Then
                MsgBox(My.Resources.NoDatatoPrint, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Function
            End If
            Frm.Show()
            Dim Pathstr As String = ""
            Dim ConfigNode() As String = ReadConfigFile.Split(";")
            Dim mServer As String = ""
            Dim mDataBase As String = ""
            Dim mUserID As String = ""
            Dim mPassword As String = ""
            Dim sql As String = ""

            If Me.RBtnSaleDate.Checked = True Then
                Pathstr = GetReportPath("PUR", "PurPOCountSaleDate.rpt")
            ElseIf Me.RBtnSup.Checked = True Then
                Pathstr = GetReportPath("PUR", "PurPOCountSup.rpt")
            ElseIf Me.RBtnDept.Checked = True Then
                Pathstr = GetReportPath("PUR", "PurPOCountDept.rpt")
            Else
                Pathstr = GetReportPath("PUR", "PurPOCountOperate.rpt")
            End If

            For i As Integer = 0 To ConfigNode.Length - 1
                If ConfigNode(i).Split("=")(0).ToLower = "Server".ToLower Then
                    mServer = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "DataBase".ToLower Then
                    mDataBase = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Uid".ToLower Then
                    mUserID = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Pwd".ToLower Then
                    mPassword = ConfigNode(i).Split("=")(1)
                End If
            Next

            Dim myReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim myParameterValues As New CrystalDecisions.Shared.ParameterValues
            Dim myDiscreteValue As New CrystalDecisions.Shared.ParameterDiscreteValue

            Dim logonInfo As New CrystalDecisions.Shared.TableLogOnInfo
            Dim table As CrystalDecisions.CrystalReports.Engine.Table
            myReportDoc.Load(Pathstr)

            For Each table In myReportDoc.Database.Tables
                logonInfo = table.LogOnInfo
                With logonInfo.ConnectionInfo
                    .ServerName = mServer
                    .DatabaseName = mDataBase
                    .UserID = mUserID
                    .Password = mPassword
                End With
                table.ApplyLogOnInfo(logonInfo)
            Next


            If Me.TabControl1.SelectedIndex = 0 Then
                If MasterDS.Tables(0).Rows.Count > 0 Then
                    myReportDoc.SetDataSource(MasterDS.Tables(0))
                End If
            Else
                myReportDoc.SetDataSource(CType(DataGridView1.DataSource, DataTable))
                myReportDoc.SetParameterValue("Date ", FormatDate(Me.DateTimePicker4.Value))
                myReportDoc.SetParameterValue("Date ", FormatDate(Me.DateTimePicker3.Value))
                myReportDoc.SetParameterValue("f.listA ", PubUserCode)

            End If



            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = myReportDoc
            Dim TxtStartDate As CrystalDecisions.CrystalReports.Engine.TextObject = myReportDoc.ReportDefinition.ReportObjects("StartDate")
            Dim TxtEndDate As CrystalDecisions.CrystalReports.Engine.TextObject = myReportDoc.ReportDefinition.ReportObjects("EndDate")
            TxtStartDate.Text = Format(Me.DateTimePicker3.Value.ToString("yyyy/MM/dd"), "yyyy/MM/dd")
            TxtEndDate.Text = Format(Me.DateTimePicker4.Value.ToString("yyyy/MM/dd"), "yyyy/MM/dd")
            My.Forms.Frm_Report.CrystalReportViewer1.Zoom(1)
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False

            Frm.Dispose()
            Frm_Report.ShowDialog()

        Catch ex As Exception
            MsgBox(My.Resources.ErrPrint & ex.Message & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function
#End Region

#Region "Sub adn Function "

    Private Sub OrdeModeItem()
        Try
            Dim Dset As DataSet
            Dim sql As String = ""
            sql = "select distinct ListA from BSC_OtherDefineB where ItemNo = '16'"
            Dset = Exec(sql, E_ExecType.DataSet)
            Me.CBOrdeStatus.DataSource = Dset.Tables(0)
            Me.CBOrdeStatus.DisplayMember = "ListA"
        Catch ex As Exception
            MessageBox.Show("Initialize:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try

    End Sub

    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try
            Dim URow As DataGridViewRow = Me.DataGridView1.CurrentRow
            Select Case type
                Case ButtonType.Browse
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True
                    End With
            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub CrystalReportViewer1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub CmbOrdeMode_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ButtonFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonFind.Click
        Try
            BindMasterGrid()
            Dim sql As String = ""
            Dim WhereStr As String = ""

            If Me.CBOrdeStatus.Text.Length > 0 Then
                WhereStr += "and f.listA = '" & Me.CBOrdeStatus.Text.Trim & "'"
            End If

            If Me.DateTimePicker3.Value.ToString.Length > 0 And Me.DateTimePicker4.Value.ToString.Length <= 0 Then
            ElseIf Me.DateTimePicker3.Value.ToString.Length <= 0 And Me.DateTimePicker4.Value.ToString.Length >= 0 Then
            ElseIf Me.DateTimePicker3.Value.ToString.Length >= 0 And Me.DateTimePicker4.Value.ToString.Length >= 0 Then
                WhereStr += " and Date between '" & Format(Me.DateTimePicker3.Value.ToString("yyyy-MM-dd"), "yyyy-MM-dd") & "' and '" & Format(Me.DateTimePicker4.Value.ToString("yyyy-MM-dd"), "yyyy-MM-dd") & "'"
            End If

            If Me.RBtnSaleDate.Checked = True Then
                sql = "select Date=Convert(varchar(10),a.Date,121), count( Distinct a.Num) as Num,sum(b.TAmount) as TAmount,sum(b.TAmount* a.discount/100) as disamount, sum ( b.TAmount*(1-a.discount/100)) as Amount " & vbCrLf
                sql &= "FROM Pur_POA a inner join Pur_POB b on a.Num=b.Num left join (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= "where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='CurrencyDefine'))c on a.Currency=c.ListCode " & vbCrLf
                sql &= " inner join (SELECT fCode,fCName FROM BSC_GoodsType where fParentID=0 ) d on a.Dept=d.fCode left join BSC_Supplier e on a.SupplierCode=e.Code " & vbCrLf
                sql &= "inner join (select ListCode,ListA from dbo.BSC_OtherDefineB  where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA " & vbCrLf
                sql &= "  where ItemCode='BillstatusDefine'))f on  a.BillstatusID=f.ListCode inner join  (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='Payterm') )g on a.Payterm=g.ListCode  where 1=1 " & vbCrLf
                sql &= WhereStr
                sql &= " GROUP BY  a.date" & vbCrLf
            End If
            If Me.RBtnSup.Checked = True Then
                sql = "select SupplierCode=CASE WHEN  ISNULL(e.CnName,'')='' THEN e.EnName WHEN LEN(e.CnName)=0 THEN e.EnName ELSE e.CnName END,count( Distinct a.Num) as Num,sum(b.TAmount) as TAmount,sum(b.TAmount* a.discount/100) as disamount, sum ( b.TAmount*(1-a.discount/100)) as Amount " & vbCrLf
                sql &= "FROM Pur_POA a inner join Pur_POB b on a.Num=b.Num left join (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= "where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='CurrencyDefine'))c on a.Currency=c.ListCode " & vbCrLf
                sql &= " left join (SELECT fCode,fCName FROM BSC_GoodsType where fParentID=0 ) d on a.Dept=d.fCode left join BSC_Supplier e on a.SupplierCode=e.Code " & vbCrLf
                sql &= "left join (select ListCode,ListA from dbo.BSC_OtherDefineB  where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA " & vbCrLf
                sql &= "  where ItemCode='BillstatusDefine'))f on  a.BillstatusID=f.ListCode left join  (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='Payterm') )g on a.Payterm=g.ListCode  where 1=1 " & vbCrLf
                sql &= WhereStr
                sql &= " GROUP BY   e.CnName,e.EnName" & vbCrLf
            End If
            If Me.RBtnDept.Checked = True Then
                sql = "select Dept=d.fCName, count( Distinct a.Num) as Num,sum(b.TAmount) as TAmount,sum(b.TAmount* a.discount/100) as disamount, sum ( b.TAmount*(1-a.discount/100)) as Amount" & vbCrLf
                sql &= "FROM Pur_POA a inner join Pur_POB b on a.Num=b.Num left join (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= "where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='CurrencyDefine'))c on a.Currency=c.ListCode " & vbCrLf
                sql &= " left join (SELECT fCode,fCName FROM BSC_GoodsType where fParentID=0 ) d on a.Dept=d.fCode left join BSC_Supplier e on a.SupplierCode=e.Code " & vbCrLf
                sql &= "left join (select ListCode,ListA from dbo.BSC_OtherDefineB  where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA " & vbCrLf
                sql &= "  where ItemCode='BillstatusDefine'))f on  a.BillstatusID=f.ListCode left join  (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='Payterm') )g on a.Payterm=g.ListCode  where 1=1 " & vbCrLf
                sql &= WhereStr
                sql &= " GROUP BY   d.fCName" & vbCrLf
            End If
            If Me.RBtnOperate.Checked = True Then
                sql = "select a.EnterBy,count( Distinct a.Num) as Num,sum(b.TAmount) as TAmount,sum(b.TAmount* a.discount/100) as disamount, sum ( b.TAmount*(1-a.discount/100)) as Amount " & vbCrLf
                sql &= "FROM Pur_POA a inner join Pur_POB b on a.Num=b.Num left join (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= "where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='CurrencyDefine'))c on a.Currency=c.ListCode " & vbCrLf
                sql &= " left join (SELECT fCode,fCName FROM BSC_GoodsType where fParentID=0 ) d on a.Dept=d.fCode left join BSC_Supplier e on a.SupplierCode=e.Code " & vbCrLf
                sql &= "left join (select ListCode,ListA from dbo.BSC_OtherDefineB  where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA " & vbCrLf
                sql &= "  where ItemCode='BillstatusDefine'))f on  a.BillstatusID=f.ListCode left join  (select ListCode,ListA from dbo.BSC_OtherDefineB " & vbCrLf
                sql &= " where ItemNo=(select Top 1 ID from dbo.BSC_OtherDefineA where ItemCode='Payterm') )g on a.Payterm=g.ListCode  where 1=1 " & vbCrLf
                sql &= WhereStr
                sql &= "  GROUP BY  a.EnterBy" & vbCrLf
            End If
            MasterDS = ReturnDataset(sql)
            Me.DataGridView1.DataSource = MasterDS.Tables(0)
            Me.SetButton(ButtonType.Browse, True)
        Catch ex As Exception
            MsgBox("BtnFind_Click:" & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub Frm_PURPOCount_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        BindMasterGrid()
        OrdeModeItem()
    End Sub

    Private Sub BindMasterGrid()
        Dim mTable As New DataTable()
        Try
            With mTable
                .Columns.Add("date")
                .Columns.Add("Num")
                .Columns.Add("TAmount")
                .Columns.Add("Disamount")
                .Columns.Add("Amount")
                .Columns.Add("SupplierCode")
                .Columns.Add("Dept")
                .Columns.Add("EnterBy")
            End With
            MasterDS = New DataSet
            MasterDS.Tables.Add(mTable)
            Me.DataGridView1.DataSource = MasterDS.Tables(0)

            With Me.DataGridView1
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHashTable(1).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            End With

        Catch ex As Exception
            MsgBox("BindDetailGrid", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mTable = Nothing
        End Try
    End Sub

    Private Function BindHashTable(Optional ByVal Index As Integer = 0) As Hashtable
        Dim mHash As New Hashtable
        Try
            With mHash
                .Add("date", "采購日期")
                .Add("Num", "訂單數目")
                .Add("TAmount", "訂單金額")
                .Add("Disamount", "折扣金額")
                .Add("Amount", "折后金額")
                .Add("SupplierCode", "供應商名稱")
                .Add("Dept", "部門名稱")
                .Add("EnterBy", "操作員")
            End With
            Return mHash
        Catch ex As Exception
            Return Nothing
            MsgBox("BindHashTable" & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mHash = Nothing
        End Try
    End Function

    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

    End Sub

    Private Sub DataGridView1_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DataGridView1.RowPostPaint
        Try
            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            Dim SBrush As New SolidBrush(DGView.RowHeadersDefaultCellStyle.ForeColor)
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, SBrush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MessageBox.Show("DataGridViewstorage_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub DataGridView1_ColumnWidthChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DataGridView1.ColumnWidthChanged
    End Sub

    Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs)
    End Sub

#End Region


End Class
